<template>
  <div>
    <h2>挖矿</h2>
    <form @submit.prevent="startMining">
      <div>
        <label>目标账号:</label>
        <input v-model="account" placeholder="请输入目标账号" required />
      </div>
      <button type="submit">启动挖矿</button>
      <button type="button" @click="pauseMining" :disabled="!isMining">暂停挖矿</button>
      <button type="button" @click="stopMining" :disabled="!isMining">停止挖矿</button>
    </form>
    <div v-if="result">
      <p><strong>挖矿结果:</strong> {{ result.message }}</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref } from 'vue'

export default {
  name: 'Mining',
  setup() {
    const account = ref('')
    const result = ref(null)
    const isMining = ref(false)
    // let miningInterval = null

    const sendMiningCommand = async (action) => {
      try {
        await axios.post('/api/mine', { account: account.value, action })
      } catch (error) {
        console.error(error)
        alert(`${action.charAt(0).toUpperCase() + action.slice(1)}挖矿失败`)
        if (action !== 'stop') {
          isMining.value = true // 如果不是停止操作，恢复挖矿状态
        }
      }
    }

    const startMining = async () => {
      if (isMining.value) return
      isMining.value = true
      await sendMiningCommand('start')
      // miningInterval = setInterval(async () => {
      //   try {
      //     const payload = { account: account.value, action: 'mine' }
      //     const response = await axios.post('/api/mine', payload)
      //     // 假设返回的数据格式为：{ message: '挖矿成功/失败信息' }
      //     result.value = response.data
      //   } catch (error) {
      //     console.error(error)
      //     alert('挖矿失败')
      //   }
      // }, 5000) // 每5秒挖矿一次，可以根据实际情况调整
    }

    const pauseMining = async () => {
      // clearInterval(miningInterval)
      isMining.value = false
      await sendMiningCommand('pause')
    }

    const stopMining = async () => {
      // clearInterval(miningInterval)
      isMining.value = false
      result.value = null // 清空结果
      await sendMiningCommand('stop')
    }

    return { account, startMining, pauseMining, stopMining, result, isMining }
  }
}
</script>